<template>
    <rx-dialog class="rx-userDialog" :options="config" @close="close" @confirm="confirm">
        <rx-layout>
            <template v-slot:header>
                <div class="RxFilters-input">
                    <my-icon size="1rem" type="icon-Vue3_search"></my-icon>
                    <input :placeholder="i18n('enterGroup','请输入用户名搜索')" v-model="searchUser"/>
                </div>
                <uni-breadcrumb style="margin: 0.5rem;overflow: auto;" separator="/">
                    <uni-breadcrumb-item
                        v-for="(route,index) in nav"
                        :key="index"
                        @click="navClick(route)"
                    >
                        {{ route.title }}
                    </uni-breadcrumb-item>
                </uni-breadcrumb>
                <div class="user-center" v-if="userShow && showDimId && !searchUser">
                    <ul>
                        <li class="user-group" v-for="item in dimData" @click="selectDimNode(item)">
                            <my-icon type="icon-wenjianziliao" size="1.4rem"></my-icon>
                            <span>{{ item.text }}</span>
                        </li>
                    </ul>
                </div>
            </template>
            <template v-slot:center style="padding: 0px">
                <div class="user-center" v-if="searchUser">
                    <ul>
                        <li class="user-list" v-for="item in searchUserData" @click="setChecked(item)">
                            <div class="user-list-icon">
                                <my-icon size="1rem" type="icon-Vue3_user"></my-icon>
                            </div>
                            <span>{{ item.fullName }}</span>
                            <radio v-if="single" :checked="selectUserKey.includes(item.userId)"
                                   @click="setChecked(item)"/>
                            <checkbox v-else :checked="selectUserKey.includes(item.userId)" @click="setChecked(item)"/>
                        </li>
                        <div v-if="total>pages" style="text-align: center;line-height: 2rem" @click="loadMoreSearch">
                            {{ i18n('clickLoadMore', '点击加载更多') }}
                        </div>
                    </ul>
                </div>
                <div class="user-center" v-else-if="!userShow || !showDimId">
                    <ul>
                        <li class="user-group" v-for="item in treeData" @click="rowClick(item)">
                            <my-icon type="icon-wenjianziliao" size="1.4rem"></my-icon>
                            <span>{{ item.title }}</span>
                        </li>
                    </ul>
                    <ul>
                        <li class="user-list" v-for="item in userData" @click="setChecked(item)">
                            <div class="user-list-icon">
                                <my-icon size="1rem" type="icon-Vue3_user"></my-icon>
                            </div>
                            <span>{{ item.fullName }}</span>
                            <radio v-if="single" :checked="selectUserKey.includes(item.userId)"
                                   @click="setChecked(item)"/>
                            <checkbox v-else :checked="selectUserKey.includes(item.userId)" @click="setChecked(item)"/>
                        </li>
                    </ul>
                    <div v-if="total>pages" style="text-align: center;line-height: 2rem" @click="loadMore">
                        {{ i18n('clickLoadMore', '点击加载更多') }}
                    </div>
                </div>
                <RxLoading v-if="Loading"></RxLoading>
            </template>
            <template v-slot:footer v-if="selectData.length>0">
                <div class="rx-footer">
                    <div class="rx-footer-selected">{{ i18n('selected', '已选') }}({{ selectData.length }})</div>
                    <div @click="footerClean" class="rx-footer-clean">{{ i18n('clear', '清除') }}</div>
                </div>
                <div class="user-select">
                    <div class="user-selectData" v-for="user in selectData">
                        <div class="user-list-icon">
                            <my-icon size="1rem" type="icon-people_fill"></my-icon>
                        </div>
                        <span class="user-selectData-name">{{ user.fullName }}</span>
                        <my-icon @click="setChecked(user)" class="user-selectData-delete" size="1.2rem"
                                 type="icon-icon-test26"></my-icon>
                    </div>
                </div>
            </template>
        </rx-layout>
    </rx-dialog>
</template>

<script>
import Api from "@/api/Api";
import BaseDialogComponent from "@/components/layer/BaseDialogComponent.js";
import RxLoading from '@/components/RxLoading'
import RxDialog from "@/components/RxDialog";
import RxLayout from '@/components/RxLayout'

export default {
    name: "RxUserDialog",
    mixins: [BaseDialogComponent],
    components: {
        RxLoading,
        RxDialog,
        RxLayout
    },
    data() {
        return {
            dimData: [],
            curDim: {},
            treeData: [],//部门树
            queryParam: {dimId: 1},
            queryDatas: {},
            expandedKeys: [],
            total: 0,
            pages: 1,
            pageSizes: 20,
            groupSearchName: "",
            userData: [],
            searchUserData: [],
            selectUserKey: [],//选中的key
            selectData: [],//选中的人员数据
            selectTab: 'group',
            field: 'userId',
            curVal: [],
            searchUser: '',//搜索的用户
            //接收dimIds
            localDimIds: '',
            Loading: true,
            /*导航数据*/
            nav: [
                {title: this.i18n('RootOrganization', '根组织'), key: '_indexHome', groupId: 'home'}
            ],
            config: {
                title: this.i18n('selectUser', '选择用户')
            },
            eventName: '',
            /**
             * 传入的用户,value
             */
            value: [],
            /**
             * 单选多选
             */
            single: false,
            /**
             *指定维度ID,默认为1
             */
            dimIds: "1",
            /**
             * 租户ID
             */
            tenantId: "1",
            /**
             * 显示维度.
             */
            organization: false,
            //是否展示维度
            showDimId: true,
            //指定维度ID,默认为1
            dimId: "",
            //指定等级
            initRankLevel: "",
            //指定展示某个组的用户
            groupId: "",
            //指定多个用户组
            groups: [],
            /**
             * 只查询有效的用户。
             */
            onlyValid: true,
            //指定组织；selOrg(指定用户组) relOrg(关联组织) allOrg(所有组织) curOrg(当前组织)
            orgconfig: "",
            userShow: true,
            //当前是否是最外层
        }
    },
    onLoad(params) {
        let openUserParams = uni.getStorageSync('openUserParams')
        let obj = openUserParams.params;
        //传入参数据
        for (let name in obj) {
            this.$data[name] = obj[name]
        }
        this.eventName = openUserParams.eventName;
        this.curVal = this.value;
        this.localDimIds = this.dimIds;
        this.inits();
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "allLang", key);
        },
        confirm() {
            //确定
            let self = this;
            uni.navigateBack({
                delta: 1,
                success: function () {
                    uni.$emit(self.eventName, self.selectData)
                }
            })
        },
        close() {
            let self = this;
            uni.navigateBack({
                delta: 1,
                success: function () {
                    uni.$emit(self.eventName, [])
                }
            })
        },
        inits() {
            let self = this;
            //指定用户组
            if (this.groupId) {
                //查询左树用户
                this.queryParam.groupId = this.groupId;
            } else if (this.groups && this.groups.length > 0) {
                this.queryParam.groupId = this.groups.join(",");
            }
            if (this.tenantId) {
                this.queryParam.tenantId = this.tenantId;
            }
            this.loadDims(function () {
                self.initLoadDeps();
            });
            // this.loadUsers(true);
            this.setInitSelectKeys()
        },
        //同时指定维度、维度等级，则以平铺显示
        isSelDimIdAndLevel() {
            if ("allOrg" == this.orgconfig && this.dimId && this.initRankLevel) {
                return true;
            }
            return false;
        },
        selectDimNode(item) {
            let selKeys = item.dimId
            this.userShow = false
            this.localDimIds = selKeys;
            this.expandedKeys = []
            this.label = 'title';
            this.curDim = this.dimData.find(field => {
                return field.value == selKeys
            });
            this.orgData = [];
            this.groupSearchName = "";
            this.loadDeps({dimId: selKeys, initRankLevel: this.initRankLevel, tenantId: this.tenantId});
            this.queryParam = {};
            this.queryParam.dimId = this.localDimIds;
            this.queryDatas['dim'] = this.queryParam.dimId;
            this.userData = [];
            this.nav.push({title: item.name, key: 'root', groupId: item.dimId})
        },
        /*
        获取组织
         */
        loadDims(callback) {
            let self = this;
            Api.getDimList(this.tenantId).then(res => {
                const dimData = res.data;
                this.Loading = false;
                this.dimData = dimData.map(dim => {
                    if (dim.dimId == self.localDimIds) {
                        self.curDim = dim;
                    }
                    return {value: dim.dimId, text: dim.name, ...dim};
                })
                if (!this.localDimIds) {
                    this.localDimIds = this.dimData[0].value;
                }
                callback();
            })
        },
        //加载部门树
        loadDeps(params, callback) {
            Api.getGroupListByDimId(params).then(resp => {
                this.Loading = false
                let data = resp.data;
                let temp = [];
                for (let i = 0; i < data.length; i++) {
                    let res = data[i];
                    let obj = {
                        title: res.name,
                        groupId: res.groupId,
                        key: res.key
                    }
                    if (res.childAmount > 0) {
                        obj.children = []
                    }
                    temp.push(obj)
                }
                this.treeData = [...temp];
                callback && callback(this.treeData);
            });
        },
        initLoadDeps() {
            var selectGroups = [];
            let selectGroup = "";
            if (this.groups && this.groups.length > 0) {
                selectGroups.push(...this.groups);
            }
            if (this.groupId) {
                selectGroups.push(this.groupId);
            }
            selectGroup = JSON.stringify(selectGroups);
            let self = this;

            let conf = {
                orgconfig: this.orgconfig,
                dimId: this.localDimIds,
                initRankLevel: this.initRankLevel,
                tenantId: this.tenantId,
                groups: selectGroup
            };
            this.loadDeps(conf, function (data) {
                if (!data || !data[0]) {
                    return;
                }
                let {groupId} = data[0];
                self.expandedKeys.push(groupId);
                // self.expandClick(true,data[0])
                self.positionGroupArr = [data[0]];
            });
        },
        loadMore() {
            this.pages++;
            this.loadUsers('', this.pages, this.pageSizes)
        },
        //加载用户列表
        loadUsers(init, pageNo, pageSize) {

            if ("comonUser" == this.selectTab) {
                return;
            }
            var url = '/api-user/user/org/osUser/getAllUserByGroupId';
            this.queryDatas = {
                groupId: this.queryParam.groupId,
                name: this.queryParam.Q_FULLNAME__S_LK,
                userNo: this.queryParam.Q_USER_NO__S_LK,
                email: this.queryParam.Q_EMAIL__S_LK,
                dim: this.localDimIds || this.queryParam.dimId,
                rankLevel: this.initRankLevel,
                tenantId: this.tenantId
            }
            //默认只查询有效的。
            if (this.onlyValid) {
                this.queryDatas.status = "1";
            }
            //查询在职用户
            //pageNo pageSize是在分页的时候传进来的；如果没有取默认
            let parameter = {
                pageNo: pageNo || this.pages,
                pageSize: pageSize || this.pageSizes,
                sortField: '',
                sortOrder: "asc",
                params: {}
            }
            if (parameter) {
                parameter.params = Object.assign(parameter.params, this.queryDatas);
            }
            this.getData(url, parameter, init)
        },
        //获取用户列
        getData(url, parameter, init) {
            let self = this;
            Api.getAjax().postJson(url, parameter).then(res => {
                let rtn = self.handError(res);
                this.Loading = false;
                if (rtn) {
                    return;
                }
                let {data, totalPage} = res.result;
                self.userData = [...self.userData, ...data];
                self.total = totalPage;
                if (init) {
                    this.setInitSelectKeys();
                }
            })
        },
        setInitSelectKeys() {
            if (this.curVal && this.curVal.length > 0) {
                this.selectUserKey = this.curVal.map(item => {
                    return item['userId'];
                })
                this.selectData = [...this.curVal];
            }
        },
        listClick(checked, row) {
            let _index = this.selectData.findIndex(item => {
                if (item['userId']) {
                    return item['userId'] == row['userId']
                } else {
                    return item['key'] == row['userId']
                }
            });

            if (checked) {
                //已被选中
                if (_index > -1) {
                    return;
                }
                if (this.single) {//单选
                    this.selectData = [row];
                    return;
                }
                this.selectData.push(row);
            } else {
                if (this.single) {//单选
                    this.selectData = [];
                    return;
                }
                if (_index == -1) {
                    return;
                }
                this.selectData.splice(_index, 1)
            }
        },
        handError(res) {
            //如果是数组则直接返回。
            if (Object.prototype.toString.call(res) == "[object Array]") {
                return false;
            }
            if (!res.success) {
                this.$message.error(this.i18n('oadingSysError', '后台数据加载出错!'));
                return true;
            }
            return false;
        },
        navClick(route) {
            if (route.key == '_indexHome') {
                this.userData = [];
                this.inits();
                this.userShow = true
            } else if (route.key == 'root') {
                this.userData = [];
                this.loadDeps({dimId: route.groupId, initRankLevel: this.initRankLevel, tenantId: this.tenantId});
            } else {
                this.rowClick(route)
            }
            let idx = this.nav.findIndex(item => item.key === route.key)
            this.nav = this.nav.slice(0, idx + 1);
        },
        //组织树选择
        rowClick(tree) {
            let self = this;
            self.nav.push(tree)
            if (!this.isSelDimIdAndLevel()) {
                Api.getParentGroup(tree.groupId, self.initRankLevel).then(data => {
                    let treeData = [];
                    for (let i = 0; i < data.length; i++) {
                        let rs = data[i];
                        let obj = {
                            title: rs.name,
                            groupId: rs.groupId,
                            key: rs.key
                        }
                        if (rs.childAmount > 0) {
                            obj.children = []
                        }
                        treeData.push(obj);
                    }
                    self.treeData = treeData;
                    self.queryParam.groupId = tree.groupId
                    self.userData = [];
                    self.loadUsers()
                });
            } else {
                self.treeData = [];
                self.queryParam.groupId = tree.groupId
                self.userData = [];
                self.loadUsers()
            }
        },
        //选中用户
        setChecked(row) {
            let key = this.field;
            let checked = !this.selectUserKey.includes(row.userId)
            if (checked) {
                if (this.single) {//单选
                    this.selectUserKey[0] = row[key];
                } else if (!this.selectUserKey.includes(row[key])) {
                    this.selectUserKey.push(row[key]);
                }
            } else {
                if (this.single) {//单选
                    this.selectUserKey = []
                } else if (this.selectUserKey.includes(row[key])) {
                    this.selectUserKey.splice(this.selectUserKey.indexOf(row[key]), 1);
                }
            }
            this.listClick(checked, row)
        },
        footerClean() {
            this.selectData = [];
            this.selectUserKey = [];
        },
        //查询
        getUserData() {
            let parames = {
                scope: {},
                pageNo:this.pages,
                pageSize:this.pageSizes,
            };
            parames.status = "1";
            parames.val = this.searchUser
            let self = this;
            Api.searchUserData(parames).then(res => {
                let result = res.result;
                let data = result.data;
                self.searchUserData = [...self.searchUserData, ...data];
                self.total = result.totalPage
            }).catch(err => {
            })
        },
        loadMoreSearch(){
            this.pages++;
            this.getUserData()
        }
    },
    watch: {
        searchUser() {
            this.total = 0;
            this.pages = 1;
            this.pageSizes = 20;
            this.searchUserData = [];
            this.getUserData()
        }
    }
}
</script>

<style scoped>
.user-data-select >>> .uni-select__input-box {
    flex-direction: row-reverse !important;
}

.user-data-select >>> .uni-select__input-text {
    padding-left: 0.5rem;
}

.rx-footer {
    display: flex;
    margin-bottom: 0.5rem;
}

.rx-footer-selected {
    color: rgba(0, 0, 0, 0.65);
    font-size: 0.8rem;
    flex: 1;
}

.rx-footer-clean {
    font-size: 0.8rem;
    color: rgba(255, 81, 81, 1);
}

.rx-userDialog >>> .m-mobile-roll {
    padding: 0px !important;
}

.rx-userDialog >>> .RxLayout-footer {
    margin-top: 0.5rem;
}

.rx-userDialog >>> .RxLayout-header {
    border-bottom: 1px solid rgba(232, 232, 232, 1);
}

.user-center {
    background: white;
    padding: 0rem 0.5rem;
}

.rx-userDialog >>> .RxLayout-center {
    padding: 0px !important;
    margin-top: 0.5rem;
}

.user-group {
    display: flex;
    align-items: center;
    padding: 0.5rem 0px;
    border-bottom: 1px solid rgba(232, 232, 232, 1);
}

.user-group:last-of-type {
    border-bottom: none;
}

.user-group i {
    color: rgba(255, 149, 43, 1);
    margin-right: 9px;
}

.user-group span {
    letter-spacing: 0px;
    line-height: 21px;
    color: rgba(0, 0, 0, 0.85);
}

.user-list {
    display: flex;
    align-items: center;
    padding: 0.5rem 0px;
    border-bottom: 1px solid rgba(232, 232, 232, 1);
}

.user-list-icon {
    width: 28px;
    height: 28px;
    opacity: 1;
    border-radius: 100px;
    background: rgba(66, 133, 244, 1);
    display: flex;
    justify-content: center;
    align-items: center;
    color: white;
    margin-right: 9px;
}

.user-list span {
    letter-spacing: 0px;
    line-height: 21px;
    color: rgba(0, 0, 0, 0.85);
    flex: 1;
}

.user-bottom {
    display: flex;
    grid-gap: 10px;
    margin-top: 0.5rem;
}

.user-ok {
    flex: 1;
    height: 45px;
    line-height: 45px;
    color: white;
    opacity: 1;
    border-radius: 8px;
    background: rgba(66, 133, 244, 1);
    display: flex;
    justify-content: center;
    align-items: center;
}

.user-cancel {
    flex: 1;
    height: 45px;
    line-height: 45px;
    opacity: 1;
    border: 1px solid rgba(232, 232, 232, 1);
    color: rgba(0, 0, 0, 0.65);
    border-radius: 8px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.user-select {
    display: flex;
    flex-wrap: wrap;
    max-height: 9.5rem;
    overflow: auto;
    padding-top: 0.25rem;
}

.user-selectData {
    font-size: .7rem;
    border-radius: 8px;
    background: rgba(242, 242, 242, 1);
    display: flex;
    justify-content: flex-start;
    align-items: center;
    padding: 8px 8px 8px 8px;
    display: flex;
    align-items: center;
    position: relative;
    margin: 0rem 0.5rem 0.5rem 0rem;
}

.user-selectData-name {
    line-height: 19.6px;
    color: rgba(0, 0, 0, 0.65);
}

.user-selectData-delete {
    color: rgba(255, 81, 81, 1);
    position: absolute;
    right: -0.4rem;
    top: -0.25rem;
}

.RxFilters-input {
    flex: 1;
    height: 40px;
    opacity: 1;
    border-radius: 8px;
    background: rgba(242, 242, 242, 1);
    display: flex;
    justify-content: flex-start;
    align-items: center;
    padding: 0px 8px;
    font-size: 15px;
    font-weight: 500;
    color: rgba(0, 0, 0, 0.3);
}

.RxFilters-input i {
    color: #555555;
    font-size: 1.5rem;
    margin-right: 0.5rem;
}

.user-data-select {
    margin-top: 0.3rem;
}

.user-data-select >>> .uni-select {
    border: none !important;
}
</style>
